# encoding=utf-8
import pymysql

db = None
cursor = None

def connect_mysql():
    global db
    global cursor
    db = pymysql.connect(
                         host='82.157.127.245',
                         #host='127.0.0.1',
                         user='root',
                         port=3306,
                         password='ydsungan0406',
                         database='weibo',
                         charset='utf8mb4')
    cursor = db.cursor()
def close_mysql():
    if cursor is not None:
        cursor.close()
    if db is not None:
        db.close()

def get_mblog_by_docids(docids):

    connect_mysql()
    res_list = []
    sql = "select user_name, text, pic_urls, video_url, date, sentiment from mblog2 where id=%s"
    for docid in docids:
        cursor.execute(sql, docid)
        res_list.append(cursor.fetchone())
    close_mysql()
    return res_list



def get_mblog_by_page(size, page):
    connect_mysql()
    sql = "select id, text from mblog2 limit %s, %s"
    start = (page - 1) * size
    end = page * size
    cursor.execute(sql, (start, end))
    res = cursor.fetchall()
    close_mysql()
    return res

def get_mblog_by_start_id(start_id, size):
    connect_mysql()
    sql = "select id, text from mblog2 where id >= %s limit %s"
    cursor.execute(sql, (start_id, size))
    res = cursor.fetchall()
    close_mysql()
    return res

def update_sentiment_by_id(data):
    # data = [(1,1), (2,1), (3,-1)]
    connect_mysql()
    sql = "update mblog2 set sentiment=%s where id=%s;"
    for id, sentiment in data:
        cursor.execute(sql, [sentiment, id])
    db.commit()
    close_mysql()

if __name__ == "__main__":
    #get_mblog_by_page(10, 1)
    #get_count_by_uid("2803301701")
    #f1()
    docid = [6540800, 6325761, 6325762, 5775877, 5858823, 6325770, 6299666, 5776917, 6553623, 6430233]
    mblogs1 = get_mblog_by_docids(docid)
    #update_sentiment_by_id([(5732731, 1)])
    print(mblogs1)